package org.nmgyjt.springboot.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

@Slf4j
public class BaseSixtyFourUtil {

    private BaseSixtyFourUtil() {
    }

    private static Base64.Encoder encoder = Base64.getEncoder();
    private static Base64.Decoder decoder = Base64.getDecoder();
    private static String UTF_8 = "UTF-8";

    /**
     * 加密
     *
     * @param str 源字符串
     * @return 加密后的字符串
     */
    public static String encodeData(String str) {
        String result = null;
        byte[] b;
        try {
            if (str != null && !"".equals(str.trim())) {
                b = str.getBytes("utf-8");
                if (b != null) {
                    result = encoder.encodeToString(str.getBytes(UTF_8));
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        return replaceBlank(result);
    }

    /**
     * 解密
     *
     * @param s 源字符串
     * @return 解密后的字符串
     */
    public static String decodeData(String s) {
        String result = null;
        if (s != null && !s.isEmpty()) {
            try {
                result = new String(decoder.decode(s), UTF_8);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return result;
    }

    /**
     * 去掉换行符
     *
     * @param str 源字符串
     * @return 去除换行符的字符串
     */
    private static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

}
